import { Injectable } from "@nestjs/common"
import { InjectModel } from "@nestjs/mongoose"
import { Model } from "mongoose"
import { IGoods } from "./goods.interface"

@Injectable()
export class GoodsService {
    constructor(
        @InjectModel('Goods')
        private readonly goodsModel: Model<IGoods>
    ) {}

    async addOneGoods(goods: IGoods) {
        // 创建一个数据
        const addGoods = await this.goodsModel.create(goods)
        // 生成的 id 也作为 key
        await this.goodsModel.findOneAndUpdate({ _id: addGoods.id }, {
            $set: {
                key: addGoods.id
            }
        })
        return addGoods
    }

    async checkOneGoods(keyQuery: { key: string }) {
        return await this.goodsModel.findOne(keyQuery)
    }

    async deleteOneGoods(keyQuery: { key: string }) {
        return await this.goodsModel.deleteOne(keyQuery)
    }

    async updateOneGoods(goods: IGoods) {
        return await this.goodsModel.findOneAndUpdate({ _id: goods.key }, { 
            $set: {
                name: goods.name,
                num: goods.num,
                description: goods.description,
                tags: goods.tags ? [...goods.tags] : []
            }
        })
    }

    async getGoodsByName(nameQuery: { name: string }) {
        return await this.goodsModel.find(nameQuery)
    }

    async allGoodsInfo() {
        return await this.goodsModel.find()
    }

    async deleteGoodsByKeys(keys: string[]) {
        return await Promise.all(keys.map(key => this.goodsModel.deleteOne({ key: key })))
    }

    async deleteAllGoods() {
        return await this.goodsModel.deleteMany()
    }
}
